package com.aynu.gulimall.gataway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import com.aynu.common.exception.BizCodeEnume;
import com.aynu.common.utils.R;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author mj
 * @version 1.0
 * @date 2021/4/16 22:33
 */
@Configuration
public class SentinelConfig {
    public SentinelConfig(){
        //定制网关流控返回
        GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() {
            //网关限流的请求就会调用这个请求
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                R error = R.error(BizCodeEnume.TO_MANY_REQUEST.getCode(), BizCodeEnume.TO_MANY_REQUEST.getMessage());
                String jsonError = JSON.toJSONString(error);
                Mono<ServerResponse> body = ServerResponse.ok().body(Mono.just(jsonError), String.class);
                return body;
            }
        });
    }
}
